// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../../lib/codemirror", "../../../mode/sql/sql"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../../lib/codemirror", "../../../mode/sql/sql"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

var htmlConfig = {
  autoSelfClosers: {'cache-ref': true, 'cache': true, /*'include': true,*/'parameter': true
       ,'id': true,'result': true,'idArg': true,'arg': true ,'case': true,'property': true
       ,'typeAlias': true,'bind': true},
  implicitlyClosed: {},
  contextGrabbers: {
      'when': {'when': true},
      'otherwise': {'when': true},
  },
  doNotChangeMode: {'mapper':true},
  sqlTags: {'sql':true,'select':true,'insert':true,'update':true,'delete':true},
  sqlUpdateTags: {'insert':true,'update':true,'delete':true},
  doNotIndent: {},
  allowUnquoted: true,
  allowMissing: false,
  caseFold: true
}

var xmlConfig = {
  autoSelfClosers: {},
  implicitlyClosed: {},
  contextGrabbers: {},
  doNotChangeMode:{},
  sqlTags: {},
  sqlUpdateTags: {},
  doNotIndent: {},
  allowUnquoted: false,
  allowMissing: false,
  allowMissingTagName: false,
  caseFold: false
}

CodeMirror.defineMode("mybatisx", function(editorConf, config_) {
  var indentUnit = editorConf.indentUnit;
  var config = {};
  var defaults = editorConf.closeMybatis?xmlConfig:(config_.htmlMode ? htmlConfig : xmlConfig);
  for (var prop in defaults) config[prop] = defaults[prop]
  for (var prop in config_) config[prop] = config_[prop]
  
  var doNotChangeMode = defaults.doNotChangeMode;
  var autoCloseTags = {emptyTags:[]};
  var autoSelfClosers = defaults.autoSelfClosers;
  var sqlTags = defaults.sqlTags;
  var sqlUpdateTags = defaults.sqlUpdateTags;
  for (var prop in autoSelfClosers) {autoCloseTags.emptyTags.push(prop);}
  editorConf.autoCloseTags = autoCloseTags;
  // Return variables for tokenizers
  var type, setStyle;
  
  var sqlMode = editorConf.sqlMode;
  if (sqlMode === "sql") sqlMode = "text/x-sql";
  var sqlConfig = CodeMirror.resolveMode(sqlMode);
  var sqlMode = CodeMirror.getMode(CodeMirror.defaults,sqlMode);
  //sqlMode.startState().tokenize(stream, state);
  var client         = sqlConfig.client || {},
  atoms          = sqlConfig.atoms || {"false": true, "true": true, "null": true},
  builtin        = sqlConfig.builtin,
  keywords       = sqlConfig.keywords,
  operatorChars  = sqlConfig.operatorChars || /^[*+\-%<>!=&|~^\/]/,
  support        = sqlConfig.support || {},
  hooks          = sqlConfig.hooks || {},
  dateSQL        = sqlConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true},
  backslashStringEscapes = sqlConfig.backslashStringEscapes !== false,
  brackets       = sqlConfig.brackets || /^[\{}\(\)\[\]]/,
  punctuation    = sqlConfig.punctuation || /^[;.,:]/ ;
  function set(str) {
      var obj = {}, words = str.split(" ");
      for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
      return obj;
  }
  //'string', with char specified in quote escaped by '\'
  function tokenLiteral(quote, backslashEscapes) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped) {
          state.tokenize = inText;//tokenBase
          break;
        }
        escaped = (backslashStringEscapes || backslashEscapes) && !escaped && ch == "\\";
      }
      return "string";
    };
  }
  function tokenComment(depth) {
    return function(stream, state) {
      var m = stream.match(/^.*?(\/\*|\*\/)/)
      if (!m) stream.skipToEnd()
      else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1)
      else if (depth > 1) state.tokenize = tokenComment(depth - 1)
      else state.tokenize = inText //tokenBase
      return "comment"
    }
  }
  function tokenBase(stream, state, ch) {
      var ch = ch || stream.next();
      if(typeof ch !== "undefined"){
    // call hooks from the mime type
        if (hooks[ch]) {
          var result = hooks[ch](stream, state);
          if (result !== false) return result;
        }

        if (support.hexNumber &&
          ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
          || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
          // hex
          // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
          return "number";
        } else if (support.binaryNumber &&
          (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
          || (ch == "0" && stream.match(/^b[01]+/)))) {
          // bitstring
          // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
          return "number";
        } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
          // numbers
          // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
          stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/);
          support.decimallessFloat && stream.match(/^\.(?!\.)/);
          return "number";
        } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
          // placeholders
          return "variable-3";
        } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
          // strings
          // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
          state.tokenize = tokenLiteral(ch);
          return state.tokenize(stream, state);
        } else if ((((support.nCharCast && (ch == "n" || ch == "N"))
            || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
            && (stream.peek() == "'" || stream.peek() == '"'))) {
          // charset casting: _utf8'str', N'str', n'str'
          // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
          return "keyword";
        } else if (support.escapeConstant && (ch == "e" || ch == "E")
            && (stream.peek() == "'" || (stream.peek() == '"' && support.doubleQuote))) {
          // escape constant: E'str', e'str'
          // ref: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE
          state.tokenize = function(stream, state) {
            return (state.tokenize = tokenLiteral(stream.next(), true))(stream, state);
          }
          return "keyword";
        } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
          // 1-line comment
          stream.skipToEnd();
          return "comment";
        } else if ((support.commentHash && ch == "#")
            || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
          // 1-line comments
          // ref: https://kb.askmonty.org/en/comment-syntax/
          stream.skipToEnd();
          return "comment";
        } else if (ch == "/" && stream.eat("*")) {
          // multi-line comments
          // ref: https://kb.askmonty.org/en/comment-syntax/
          state.tokenize = tokenComment(1);
          return state.tokenize(stream, state);
        } else if (ch == ".") {
          // .1 for 0.1
          if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i))
            return "number";
          if (stream.match(/^\.+/))
            return null
          // .table_name (ODBC)
          // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
          if (support.ODBCdotTable && stream.match(/^[\w\d_$#]+/))
            return "variable-2";
        } else if (operatorChars.test(ch)) {
          // operators
          stream.eatWhile(operatorChars);
          return "operator";
        } else if (brackets.test(ch)) {
          // brackets
          return "bracket";
        } else if (punctuation.test(ch)) {
          // punctuation
          stream.eatWhile(punctuation);
          return "punctuation";
        } else if (ch == '{' &&
            (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
          // dates (weird ODBC syntax)
          // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
          return "number";
        } else {
          //移到外面了
        }
      }
      stream.eatWhile(/^[_\w\d]/);
      var word = stream.current().toLowerCase();
      // dates (standard SQL syntax)
      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
      if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
        return "number";
      if (atoms.hasOwnProperty(word)) return "atom";
      if (builtin.hasOwnProperty(word)) return "builtin";
      if (keywords.hasOwnProperty(word)) return "keyword";
      if (client.hasOwnProperty(word)) return "string-2";
      return null;
  }
  
  function inText(stream, state) {
    function chain(parser) {
      state.tokenize = parser;
      return parser(stream, state);
    }
    
    var ch = stream.next();
    if (ch == "<") {
      if (stream.eat("!")) {
        if (stream.eat("[")) {
          if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
          else return null;
        } else if (stream.match("--")) {
          return chain(inBlock("comment", "-->"));
        } else if (stream.match("DOCTYPE", true, true)) {
          stream.eatWhile(/[\w\._\-]/);
          return chain(doctype(1));
        } else {
          return null;
        }
      } else if (stream.eat("?")) {
        stream.eatWhile(/[\w\._\-]/);
        state.tokenize = inBlock("meta", "?>");
        return "meta";
      } else {
        type = stream.eat("/") ? "closeTag" : "openTag";
        state.tokenize = inTag;
        return "tag bracket";
      }
    } else if (ch == "&") {
      var ok;
      if (stream.eat("#")) {
        if (stream.eat("x")) {
          ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
        } else {
          ok = stream.eatWhile(/[\d]/) && stream.eat(";");
        }
      } else {
        ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
      }
      return ok ? "atom" : "error";
    } else {
      /*stream.eatWhile(/[^&<]/);
        return null;*/
        return tokenBase(stream, state, ch);
    }
    
    return style;
  }
  inText.isInText = true;

  function inTag(stream, state) {
    var ch = stream.next();
    if (ch == ">" || (ch == "/" && stream.eat(">"))) {
      state.tokenize = inText;
      type = ch == ">" ? "endTag" : "selfcloseTag";
      return "tag bracket";
    } else if (ch == "=") {
      type = "equals";
      return null;
    } else if (ch == "<") {
      state.tokenize = inText;
      state.state = baseState;
      state.tagName = state.tagStart = null;
      var next = state.tokenize(stream, state);
      return next ? next + " tag error" : "tag error";
    } else if (/[\'\"]/.test(ch)) {
      state.tokenize = inAttribute(ch);
      state.stringStartCol = stream.column();
      return state.tokenize(stream, state);
    } else {
      stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
      return "word";
    }
  }

  function inAttribute(quote) {
    var closure = function(stream, state) {
      while (!stream.eol()) {
        if (stream.next() == quote) {
          state.tokenize = inTag;
          break;
        }
      }
      return "string";
    };
    closure.isInAttribute = true;
    return closure;
  }

  function inBlock(style, terminator) {
    return function(stream, state) {
      while (!stream.eol()) {
        if (stream.match(terminator)) {
          state.tokenize = inText;
          break;
        }
        stream.next();
      }
      return style;
    }
  }

  function doctype(depth) {
    return function(stream, state) {
      var ch;
      while ((ch = stream.next()) != null) {
        if (ch == "<") {
          state.tokenize = doctype(depth + 1);
          return state.tokenize(stream, state);
        } else if (ch == ">") {
          if (depth == 1) {
            state.tokenize = inText;
            break;
          } else {
            state.tokenize = doctype(depth - 1);
            return state.tokenize(stream, state);
          }
        }
      }
      return "meta";
    };
  }

  function Context(state, tagName, startOfLine) {
    this.prev = state.context;
    this.tagName = tagName || "";
    this.indent = state.indented;
    this.startOfLine = startOfLine;
    if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
      this.noIndent = true;
    if(sqlTags.hasOwnProperty(tagName)){
        this.isSqlTag = true;
        this.sqlTags = sqlTags;
    }else{
        this.isSqlTag = false;
    }
    if(sqlUpdateTags.hasOwnProperty(tagName)){
        this.isSqlUpdateTag = true;
        this.sqlUpdateTags = sqlUpdateTags;
    }else{
        this.isSqlUpdateTag = false;
    }
  }
  function popContext(state) {
    if (state.context) state.context = state.context.prev;
  }
  function maybePopContext(state, nextTagName) {
    var parentTagName;
    while (true) {
      if (!state.context) {
        return;
      }
      parentTagName = state.context.tagName;
      if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
          !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
        return;
      }
      popContext(state);
    }
  }

  function baseState(type, stream, state) {
    if (type == "openTag") {
      state.tagStart = stream.column();
      return tagNameState;
    } else if (type == "closeTag") {
      return closeTagNameState;
    } else {
      return baseState;
    }
  }
  function tagNameState(type, stream, state) {
    if (type == "word") {
      state.tagName = stream.current();
      setStyle = "tag";
      return attrState;
    } else if (config.allowMissingTagName && type == "endTag") {
      setStyle = "tag bracket";
      return attrState(type, stream, state);
    } else {
      setStyle = "error";
      return tagNameState;
    }
  }
  function closeTagNameState(type, stream, state) {
    if (type == "word") {
      var tagName = stream.current();
      if (state.context && state.context.tagName != tagName &&
          config.implicitlyClosed.hasOwnProperty(state.context.tagName))
        popContext(state);
      if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
        setStyle = "tag";
        return closeState;
      } else {
        setStyle = "tag error";
        return closeStateErr;
      }
    } else if (config.allowMissingTagName && type == "endTag") {
      setStyle = "tag bracket";
      return closeState(type, stream, state);
    } else {
      setStyle = "error";
      return closeStateErr;
    }
  }

  function closeState(type, _stream, state) {
    if (type != "endTag") {
      setStyle = "error";
      return closeState;
    }
    popContext(state);
    return baseState;
  }
  function closeStateErr(type, stream, state) {
    setStyle = "error";
    return closeState(type, stream, state);
  }

  function attrState(type, _stream, state) {
    if (type == "word") {
      setStyle = "attribute";
      return attrEqState;
    } else if (type == "endTag" || type == "selfcloseTag") {
      var tagName = state.tagName, tagStart = state.tagStart;
      state.tagName = state.tagStart = null;
      if (type == "selfcloseTag" ||
          config.autoSelfClosers.hasOwnProperty(tagName)) {
        maybePopContext(state, tagName);
      } else {
        maybePopContext(state, tagName);
        state.context = new Context(state, tagName, tagStart == state.indented);
      }
      return baseState;
    }
    setStyle = "error";
    return attrState;
  }
  function attrEqState(type, stream, state) {
    if (type == "equals") return attrValueState;
    if (!config.allowMissing) setStyle = "error";
    return attrState(type, stream, state);
  }
  function attrValueState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
    setStyle = "error";
    return attrState(type, stream, state);
  }
  function attrContinuedState(type, stream, state) {
    if (type == "string") return attrContinuedState;
    return attrState(type, stream, state);
  }

  return {
    startState: function(baseIndent) {
      var state = {tokenize: inText,
                   state: baseState,
                   indented: baseIndent || 0,
                   tagName: null, tagStart: null,
                   context: null}
      if (baseIndent != null) state.baseIndent = baseIndent
      return state
    },

    token: function(stream, state) {
      if (!state.tagName && stream.sol())
        state.indented = stream.indentation();
      if (stream.eatSpace()) return null;
      type = null;
      var style = state.tokenize(stream, state);
      if ((style || type) && style != "comment") {
        setStyle = null;
        state.state = state.state(type || style, stream, state);
        if (setStyle)
          style = setStyle == "error" ? style + " error" : setStyle;
      }
      return style;
    },

    indent: function(state, textAfter, fullLine) {
      var context = state.context;
      // Indent multi-line strings (e.g. css).
      if (state.tokenize.isInAttribute) {
        if (state.tagStart == state.indented)
          return state.stringStartCol + 1;
        else
          return state.indented + indentUnit;
      }
      if (context && context.noIndent) return CodeMirror.Pass;
      if (state.tokenize != inTag && state.tokenize != inText)
        return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
      // Indent the starts of attribute names.
      if (state.tagName) {
        if (config.multilineTagIndentPastTag !== false)
          return state.tagStart + state.tagName.length + 2;
        else
          return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
      }
      if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
      var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
      if (tagAfter && tagAfter[1]) { // Closing tag spotted
        while (context) {
          if (context.tagName == tagAfter[2]) {
            context = context.prev;
            break;
          } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
            context = context.prev;
          } else {
            break;
          }
        }
      } else if (tagAfter) { // Opening tag spotted
        while (context) {
          var grabbers = config.contextGrabbers[context.tagName];
          if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
            context = context.prev;
          else
            break;
        }
      }
      while (context && context.prev && !context.startOfLine)
        context = context.prev;
      if (context) return context.indent + indentUnit;
      else return state.baseIndent || 0;
    },

    electricInput: /<\/[\s\w:]+>$/,
    blockCommentStart: "<!--",
    blockCommentEnd: "-->",

    configuration: editorConf.closeMybatis?"xml":(config.htmlMode ? "mybatis" : "xml"),
    helperType: editorConf.closeMybatis?"mybatissql":(config.htmlMode ? "mybatis" : "xml"),

    skipAttribute: function(state) {
      if (state.state == attrValueState)
        state.state = attrState
    },

    xmlCurrentTag: function(state) {
      return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null
    },

    xmlCurrentContext: function(state) {
      var context = []
      for (var cx = state.context; cx; cx = cx.prev)
        context.push(cx.tagName)
      return context.reverse()
    },
    skipChangeMode: function(state) {
       return doNotChangeMode[state.tagName] || autoSelfClosers[state.tagName];
    },
    getRefTagContent: function (text1,text2) {
        text1 = this.clearContentComment(text1,true);
        text2 = this.clearContentComment(text2);
        var regx = new RegExp("(?<=<include +refid *= *\")(.*?)(?=\" *(/>|>.*?</include>))","ig");
        var f = text1.match(regx);
        var content = text1;
        if(f && f.length>0){
            var hasRefid = {};
            for(var i=0,k=f.length;i<k;i++){
                if(f[i] && !hasRefid[f[i]]){
                    var regx2 = new RegExp("(?<=<sql +id *= *\""+f[i]+"\" *>)(.*?)(?=</sql>)","ig");
                    var f2 = text2.match(regx2);
                    if(f2 && f2[0]){
                        hasRefid[f[i]] = true;
                        content = content.replace(new RegExp("<include +refid *= *\""+f[i]+"\" *(/>|>.*?</include>)","ig"),f2[0]);
                    }
                }
            }
        }
        return content;
    },
    clearContentComment: function (text,clearFlag) {
        text = text.replace(/'.*?'/ig,"' '").replace(/(\\n|\n|\\t|\t)/g," ").replace(/ +/g," ")
              .replace(/<!--.*?-->/g," ").replace(/<where>/g," where ")
        if(clearFlag){
            text = text.replace(new RegExp("(</((?!include)[a-z]+)+>|<((?!include)[a-z]+)+ .*?>|<((?!include)[a-z]+)+ .*?/>)","g"),"");
        }
        return text;
    }
  };
});

CodeMirror.defineMIME("text/mybatisx", {name: "mybatisx", htmlMode: true, alignCDATA: true});

});
